package homework712;

import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

//5:增加新商品的功能，要求商品号和商品名称都不能重复（即不能和已经存在的重复）
//product为商品信息节点，discount表示是否折扣，如果是折扣商品，打七折；
//factoryaddr是工厂地址；
//itemno为商品编号，name为商品名称，price为商品单价，unit是计价单位，stockcount是库存量。
public class work5 {
	public static void main(String[] args) {
		SAXReader reader = new SAXReader();
		Document doc;
		Scanner in = new Scanner(System.in);

		try {
			doc = reader.read(new File("src/homework712/products.xml"));
			Element root = doc.getRootElement();
			List<Element> list = root.selectNodes("product");
			Element e = null;
			Element newProduct = root.addElement("product");
			int b = 0;
			String b2 = null;
			for (int a = 0; a < list.size(); a++) {
				e = list.get(a);
				System.out.println("输入商品编号");
				b = in.nextInt();
				String itemno = e.selectSingleNode("itemno").getText();
				int i = Integer.parseInt(itemno);

				while (i == b) {
					System.out.println("商品编号已存在！");
					return;
				}

				System.out.println("输入商品名");
				b2 = in.next();
				Element name = (Element) e.selectSingleNode("name");
				String n = name.getText();
				while (n.equals(b2)) {
					System.out.println("商品名已存在！");
					return;
				}
				if (i != b && !n.equals(b2)) {
					break;

				}
			}

			System.out.println("输入是否打折：true or false");
			String b3 = in.next();
			System.out.println("输入商品产地");
			String b7 = in.next();
			System.out.println("输入商品价格");
			double b4 = in.nextDouble();
			System.out.println("输入商品计价单位");
			String b5 = in.next();
			System.out.println("输入商品库存量");
			int b6 = in.nextInt();

			String discount = e.attributeValue("discount");
			String factoryaddr = e.attributeValue("factoryaddr");
			newProduct.addAttribute("discount", b3);
			newProduct.addAttribute("factoryaddr", b7);
			Element c1 = newProduct.addElement("itemnoitemno");
			c1.setText("" + b);
			Element c2 = newProduct.addElement("name");
			c2.setText(b2);
			Element c3 = newProduct.addElement("price");
			c3.setText(b4 + "");
			Element c4 = newProduct.addElement("unit");
			c4.setText(b5);
			Element c5 = newProduct.addElement("stockcount");
			c5.setText(b6 + "");

			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8");
			XMLWriter xm = new XMLWriter(new FileWriter("src/homework712/products.xml"), format);
			xm.write(doc);
			xm.close();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

}
